import { fileURLToPath, URL } from 'node:url'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import externalGlobals from 'rollup-plugin-external-globals'
import vueSetupExtend from 'unplugin-vue-setup-extend-plus/vite'
const isProd: boolean = process.env.NODE_ENV === 'production'
import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'
import legacy from '@vitejs/plugin-legacy'
const plugins = [
  // externalGlobals({
  // }),
  dynamicImportVars({
    //这里配置插件在那个文件夹内生效 这里是在router文件夹内生效
    include: ['router'],
    //这里是哪些文件夹内不生效
    exclude: [],
    //插件在遇到错误时会退出构建过程。如果您将此选项设置为 true，它将引发警告，并且保持代码不变。
    warnOnError: true
  })
]

if (isProd) {
  plugins.push(
    viteCompression({
      verbose: true, // 是否在控制台中输出压缩结果
      disable: false,
      threshold: 10240, // 如果体积大于阈值，将被压缩，单位为b，体积过小时请不要压缩，以免适得其反
      algorithm: 'gzip', // 压缩算法，可选['gzip'，' brotliccompress '，'deflate '，'deflateRaw']
      ext: '.gz',
      deleteOriginFile: false // 源文件压缩后是否删除(我为了看压缩后的效果，先选择了true)
    })
  )
}
// https://vitejs.dev/config/
export default defineConfig({
  base: './',
  server: {
    host: '0.0.0.0',
    port: 3000,
    proxy: {
      '/api': {
        target: 'https://itunes.apple.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    },
    strictPort: true,
    open: false
  },
  plugins: [
    vue(),
    vueSetupExtend({}),
    nodePolyfills(),
    legacy({
      targets: ['defaults', 'not IE 11']
    })
  ],
  define: {
    // By default, Vite doesn't include shims for NodeJS/
    // necessary for segment analytics lib to work
    global: {}
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
    dedupe: ['fs', 'child_process', 'net', 'tls']
  },
  css: {
    postcss: {
      plugins: [tailwindcss, autoprefixer]
    }
  },
  build: {
    target: 'es2015',
    assetsDir: 'static', // 指定生成静态资源的存放路径
    outDir: './dist',
    emptyOutDir: false,
    cssCodeSplit: true,
    sourcemap: !isProd,
    rollupOptions: {
      plugins,
      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/name-[hash].[ext]'
      }
    }
  }
})
